@using MudBlazor
@using Nethereum.Wallet.UI.Components.WalletAccounts.PrivateKey
@using Nethereum.Wallet.UI.Components.Core.Localization
@using Nethereum.Wallet.UI.Components.Blazor.Shared
@using Microsoft.AspNetCore.Components
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.JSInterop
@using static Nethereum.Wallet.UI.Components.WalletAccounts.PrivateKey.PrivateKeyAccountEditorLocalizer
@inject IJSRuntime JSRuntime
@inject IComponentLocalizer<PrivateKeyAccountCreationViewModel> Localizer
@inject ISnackbar Snackbar

<WalletFormLayout Title="@GetTitle()"
                  Subtitle="@GetSubtitle()"
                  Steps="@formSteps"
                  CurrentStepIndex="@((int)CurrentStep)"
                  ExitText="@GetExitText()"
                  BackText="@Localizer.GetString(Keys.BackButtonText)"
                  ContinueText="@Localizer.GetString(Keys.ContinueButtonText)"
                  PrimaryText="@Localizer.GetString(Keys.AddAccountText)"
                  StepLocalizer="@Localizer"
                  ShowBack="@(CurrentStep > FormStep.Setup)"
                  ShowContinue="@(CurrentStep < FormStep.Confirm && CanContinue())"
                  ShowPrimary="@(CurrentStep == FormStep.Confirm)"
                  ContinueDisabled="@(!CanContinue())"
                  PrimaryDisabled="@(!ViewModel.CanCreateAccount)"
                  OnExit="@HandleExit"
                  OnBack="@HandleBack"
                  OnContinue="@HandleContinue"
                  OnPrimary="@CreateAccount">
    
    <div class="wallet-form-steps">
        @switch (CurrentStep)
        {
            case FormStep.Setup:
                <!-- Step 1: Account Name -->
                <WalletFormSection Title="@Localizer.GetString(Keys.AccountNameLabel)">
                    <WalletTextField @bind-Value="ViewModel.Label"
                                     LabelKey="@Keys.AccountNameLabel"
                                     PlaceholderKey="@Keys.AccountNamePlaceholder"
                                     HelpKey="@Keys.AccountNameHelperText"
                                     Localizer="@Localizer" />
                </WalletFormSection>
                
                <WalletInfoCard Severity="WalletInfoCard.WalletInfoSeverity.Info"
                                Title="@Localizer.GetString(Keys.PrivateKeyImportTitle)"
                                Description="@Localizer.GetString(Keys.PrivateKeyImportDescription)"
                                Icon="@Icons.Material.Filled.Info" />
                break;
                
            case FormStep.PrivateKey:
                <!-- Step 2: Private Key Input -->
                <WalletFormSection Title="@Localizer.GetString(Keys.PrivateKeyLabel)">
                    <WalletTextField @bind-Value="ViewModel.PrivateKey"
                                     LabelKey="@Keys.PrivateKeyLabel"
                                     HelpKey="@Keys.PrivateKeyHelperText"
                                     FieldType="WalletTextField.WalletTextFieldType.PrivateKey"
                                     ShowRevealToggle="true"
                                     IsRevealed="@ViewModel.IsRevealed"
                                     OnToggleReveal="@ViewModel.ToggleRevealAsync"
                                     ToggleRevealAriaLabel="@Localizer.GetString(Keys.ToggleVisibilityLabel)"
                                     Error="@(!string.IsNullOrEmpty(ViewModel.ErrorMessage))"
                                     ErrorText="@ViewModel.ErrorMessage"
                                     Localizer="@Localizer" />
                    
                    @if (!string.IsNullOrEmpty(ViewModel.PrivateKey))
                    {
                        <div class="validation-status">
                            <MudChip T="string" Size="Size.Small"
                                     Color="@(ViewModel.IsValidPrivateKey ? Color.Success : Color.Error)"
                                     Icon="@(ViewModel.IsValidPrivateKey ? Icons.Material.Filled.CheckCircle : Icons.Material.Filled.Error)">
                                @(ViewModel.IsValidPrivateKey ? Localizer.GetString(Keys.ValidFormatText) : Localizer.GetString(Keys.InvalidFormatText))
                            </MudChip>
                        </div>
                    }
                </WalletFormSection>
                
                <!-- Security Warning -->
                <WalletInfoCard Severity="WalletInfoCard.WalletInfoSeverity.Warning"
                                Title="@Localizer.GetString(Keys.SecurityWarningTitle)"
                                Description="@GetSecurityWarningMessage()"
                                Icon="@Icons.Material.Filled.Warning" />
                
                <!-- Format Help -->
                <WalletContentSection Title="@Localizer.GetString(Keys.SupportedFormatsTitle)" Class="spacing-normal">
                    <div class="format-help">
                        <MudText Typo="Typo.body2" Class="format-example">
                            • @Localizer.GetString(Keys.HexWithPrefixExample)
                        </MudText>
                        <MudText Typo="Typo.body2" Class="format-example">
                            • @Localizer.GetString(Keys.HexWithoutPrefixExample)
                        </MudText>
                        <MudText Typo="Typo.body2" Class="format-example">
                            • @Localizer.GetString(Keys.LengthRequirement)
                        </MudText>
                    </div>
                </WalletContentSection>
                break;
                
            case FormStep.Confirm:
                <!-- Step 3: Confirmation -->
                <WalletFormSection Title="@Localizer.GetString(Keys.ReviewAccountTitle)">
                    <div class="account-review">
                        <div class="review-field">
                            <MudText Typo="Typo.caption" Color="Color.Secondary">
                                @Localizer.GetString(Keys.AccountNameLabel)
                            </MudText>
                            <MudText Typo="Typo.body1">
                                @(string.IsNullOrWhiteSpace(ViewModel.Label) ? Localizer.GetString(Keys.AccountNamePlaceholder) : ViewModel.Label)
                            </MudText>
                        </div>
                    </div>
                </WalletFormSection>
                
                @if (!string.IsNullOrEmpty(ViewModel.DerivedAddress))
                {
                    <WalletFormSection Title="@Localizer.GetString(Keys.DerivedAddressLabel)">
                        <WalletAddressDisplay Address="@ViewModel.DerivedAddress"
                                            ComponentWidth="@ComponentWidth"
                                            IsCompact="@IsCompactMode"
                                            ShowFullAddress="true"
                                            OnCopy="@HandleAddressCopied" />
                    </WalletFormSection>
                }
                
                <!-- Final confirmation checkbox -->
                <WalletFormSection>
                    <WalletInfoCard Severity="WalletInfoCard.WalletInfoSeverity.Warning"
                                    Title="@Localizer.GetString(Keys.ImportantTitle)"
                                    Description="@Localizer.GetString(Keys.PrivateKeyBackupReminder)"
                                    Icon="@Icons.Material.Filled.Warning">
                        <div class="wallet-backup-confirmation">
                            <MudCheckBox @bind-Value="confirmBackup" 
                                         Color="Color.Primary"
                                         Class="wallet-backup-checkbox">
                                @Localizer.GetString(Keys.BackupConfirmationText)
                            </MudCheckBox>
                        </div>
                    </WalletInfoCard>
                </WalletFormSection>
                break;
        }
        
        <!-- Error/Success Messages -->
        @if (!string.IsNullOrEmpty(ViewModel.ErrorMessage))
        {
            <WalletContentSection Class="spacing-normal">
                <WalletInfoCard Severity="WalletInfoCard.WalletInfoSeverity.Error"
                                Title="@Localizer.GetString(Keys.Error)"
                                Description="@ViewModel.ErrorMessage"
                                Icon="@Icons.Material.Filled.Error" />
            </WalletContentSection>
        }
    </div>
    
</WalletFormLayout>

@code {
    [Parameter] public required PrivateKeyAccountCreationViewModel ViewModel { get; set; }
    [Parameter] public EventCallback OnAccountCreated { get; set; }
    [Parameter] public EventCallback OnBackToLogin { get; set; }
    [Parameter] public EventCallback OnBackToAccountSelection { get; set; }
    [Parameter] public bool ShowBackToLogin { get; set; } = true;
    [Parameter] public bool ShowBackToAccountSelection { get; set; } = true;
    [Parameter] public bool IsCompactMode { get; set; }
    [Parameter] public int ComponentWidth { get; set; } = 400;
    
    public enum FormStep
    {
        Setup = 0,
        PrivateKey = 1,
        Confirm = 2
    }
    
    public FormStep CurrentStep { get; set; } = FormStep.Setup;
    
    private bool confirmBackup = false;
    private List<WalletFormStep> formSteps = new();
    
    protected override void OnInitialized()
    {
        base.OnInitialized();
        
        // Reset ViewModel to ensure clean state
        ViewModel.Reset();
        
        if (string.IsNullOrEmpty(ViewModel.Label))
        {
            ViewModel.Label = "";
        }
        
        SetupFormSteps();
    }
    
    private void SetupFormSteps()
    {
        formSteps = new List<WalletFormStep>
        {
            new() { LocalizationKey = Keys.StepSetupLabel, Icon = Icons.Material.Filled.Settings },
            new() { LocalizationKey = Keys.StepPrivateKeyLabel, Icon = Icons.Material.Filled.Key },
            new() { LocalizationKey = Keys.StepConfirmLabel, Icon = Icons.Material.Filled.Shield }
        };
    }
    
    private string GetTitle()
    {
        return CurrentStep switch
        {
            FormStep.Setup => Localizer.GetString(Keys.CreatePrivateKeyAccountTitle),
            FormStep.PrivateKey => Localizer.GetString(Keys.EnterPrivateKeyTitle),
            FormStep.Confirm => Localizer.GetString(Keys.ConfirmAccountTitle),
            _ => Localizer.GetString(Keys.CreatePrivateKeyAccountTitle)
        };
    }
    
    private string GetSubtitle()
    {
        return CurrentStep switch
        {
            FormStep.Setup => Localizer.GetString(Keys.SetupAccountSubtitle),
            FormStep.PrivateKey => Localizer.GetString(Keys.PrivateKeySubtitle),
            FormStep.Confirm => Localizer.GetString(Keys.ConfirmSubtitle),
            _ => ""
        };
    }
    
    private string GetExitText()
    {
        if (ShowBackToLogin)
            return Localizer.GetString(Keys.BackToLoginText);
        if (ShowBackToAccountSelection)
            return Localizer.GetString(Keys.BackToAccountSelectionText);
        return Localizer.GetString(Keys.ExitButtonText);
    }
    
    private bool CanContinue()
    {
        return CurrentStep switch
        {
            FormStep.Setup => true, // Account name is optional
            FormStep.PrivateKey => ViewModel.IsValidPrivateKey && !string.IsNullOrEmpty(ViewModel.PrivateKey),
            FormStep.Confirm => confirmBackup && ViewModel.CanCreateAccount,
            _ => false
        };
    }
    
    private void HandleContinue()
    {
        if (CanContinue() && CurrentStep < FormStep.Confirm)
        {
            CurrentStep++;
            StateHasChanged();
        }
    }
    
    private void HandleBack()
    {
        if (CurrentStep > FormStep.Setup)
        {
            CurrentStep--;
            StateHasChanged();
        }
    }
    
    private async Task HandleExit()
    {
        if (ShowBackToLogin && OnBackToLogin.HasDelegate)
        {
            await OnBackToLogin.InvokeAsync();
        }
        else if (ShowBackToAccountSelection && OnBackToAccountSelection.HasDelegate)
        {
            await OnBackToAccountSelection.InvokeAsync();
        }
    }
    
    private async Task CreateAccount()
    {
        if (ViewModel.CanCreateAccount && confirmBackup)
        {
            await OnAccountCreated.InvokeAsync();
        }
    }
    
    private async Task HandleAddressCopied(string address)
    {
        Snackbar.Add(Localizer.GetString(Keys.CopiedToClipboard), Severity.Success);
    }
    
    private string GetSecurityWarningMessage()
    {
        return $"{Localizer.GetString(Keys.NeverShareAdvice)} {Localizer.GetString(Keys.SecureEnvironmentAdvice)} {Localizer.GetString(Keys.FullControlAdvice)}";
    }
}

